package com.skynet.supervision.utils;

import cn.hutool.core.util.ObjectUtil;
import com.google.common.collect.Lists;
import com.skynet.supervision.common.ErrCode;
import com.skynet.supervision.common.Result;
import lombok.SneakyThrows;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ObjectUtils extends ObjectUtil {
    public static <T> T cast(Object obj) {
        return (T) obj;
    }

    public static List<Field> getAllFields(Object object) {
        if (ObjectUtils.isEmpty(object)) {
            return Lists.newArrayList();
        }
        Class<?> clazz = object.getClass();
        List<Field> fieldList = Lists.newArrayList();
        while (clazz != null) {
            fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
            clazz = clazz.getSuperclass();
        }
        return fieldList;
    }

    @SneakyThrows
    public static Field getSpecifiedOrThrow(Class<?> clazz, String fieldName) {
        try {
            return clazz.getDeclaredField(fieldName);
        } catch (Exception ex) {
            throw Result.failure(ErrCode.INTERNAL_ERROR,Errors.getRootCause(ex).getMessage()).wrap();
        }
    }
}
